﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Pipra.Math.Geometry
{
    /// <summary>
    /// A polygon geometry having multiple rings which define multiple fill areas and holes.
    /// </summary>
    /// <remarks>
    /// Multiple fill rings and multiple hole rings are allowed in a polygon.
    /// </remarks>
    public class Polygon2 :
        Collection<Ring2>,
        IPlanarGeometry<double>,
        IHasMagnitude<double>,
        IHasArea<double>,
        IEquatable<Polygon2>,
        IIntersectable<Point2>,
        IHasDistance<double, Point2>,
        IContainable<Mbr>,
        ICloneable,
        ISelfIntersectable
    {

        public static bool operator ==(Polygon2 a, Polygon2 b)
        {
            return ReferenceEquals(a, b) || (!ReferenceEquals(null, a) && a.Equals(b));
        }

        public static bool operator !=(Polygon2 a, Polygon2 b)
        {
            return !ReferenceEquals(a, b) && (ReferenceEquals(null, a) || !a.Equals(b));
        }

        /// <summary>
        /// Constructs a new polygon geometry containing rings.
        /// </summary>
        public Polygon2() : this((IEnumerable<Ring2>)null) { }
        /// <summary>
        /// Constructs a new polygon geometry with no rings but prepared to store the specified number of rings.
        /// </summary>
        /// <param name="expectedCapacity">The expected number of rings the polygon will contain.</param>
        public Polygon2(int expectedCapacity) : base(new List<Ring2>(expectedCapacity)) { }
        /// <summary>
        /// Constructs a new polygon geometry composed of the given rings.
        /// </summary>
        /// <param name="rings">The rings the polygon will be composed of.</param>
        /// <remarks>The <paramref name="rings"/> are referenced instead of copied.</remarks>
        public Polygon2(IEnumerable<Ring2> rings) : base(null != rings ? new List<Ring2>(rings) : new List<Ring2>() ) { }
        /// <summary>
        /// Constructs a new polygon geometry compused of the given ring.
        /// </summary>
        /// <param name="ring">The ring the polygon will be composed of.</param>
        /// <remarks>The <paramref name="ring"/> is referenced instead of copied.</remarks>
        public Polygon2(Ring2 ring) : this(new[]{ring}) { }

        /// <summary>
        /// Forces the fill winding of the points within all contained rings to be uniform.
        /// </summary>
        /// <param name="desiredWinding">The desired winding order that defines a fill ring.</param>
        public void ForceFillWinding(PointWinding desiredWinding)
        {
            if (PointWinding.Unknown == desiredWinding)
            {
                throw new ArgumentException("desiredWinding can not be Unknown", "desiredWinding");
            }
            foreach (Ring2 ring in this)
            {
                ring.ForceFillWinding(desiredWinding);
            }
        }

        /// <summary>
        /// Creates a multi line string of the boundaries for each of the rings.
        /// </summary>
        /// <returns>A multi line string of the boundaries for each of the rings.</returns>
        public MultiLineString2 GenerateMultiLineString()
        {
            MultiLineString2 mls = new MultiLineString2(Count);
            foreach (Ring2 ring in this)
            {
                mls.Add(ring.GenerateLineString());
            }
            return mls;
        }

        internal double FindNearestSegment(Point2 location, out int ringIndex, out int segmentIndex)
        {
            if (Count > 0)
            {
                ringIndex = 0;
                double bestDist = this[0].FindNearestSegment(location, out segmentIndex);
                for (int i = 1; i < Count; i++)
                {
                    int curSegIndex;
                    double curSegDist = this[i].FindNearestSegment(location, out curSegIndex);
                    if (curSegDist < bestDist)
                    {
                        ringIndex = i;
                        segmentIndex = curSegIndex;
                        bestDist = curSegDist;
                    }
                }
                return bestDist;
            }
            ringIndex = -1;
            segmentIndex = -1;
            return Double.NaN;
        }

        internal double FindNearestVertex(Point2 location, double tolerance, out int ringIndex, out int vertexIndex)
        {
            if (Count > 0)
            {
                ringIndex = 0;
                double bestDist = this[0].FindNearestVertex(location, tolerance, out vertexIndex);
                for (int i = 1; i < Count; i++)
                {
                    int curVertIndex;
                    double curVertDist = this[i].FindNearestVertex(location, tolerance, out curVertIndex);
                    if (curVertDist < bestDist && curVertDist <= tolerance)
                    {
                        ringIndex = i;
                        vertexIndex = curVertIndex;
                        bestDist = curVertDist;
                    }
                }
                return bestDist;
            }
            ringIndex = -1;
            vertexIndex = -1;
            return Double.NaN;
        }
        /// <summary>
        /// Calculates the centroid.
        /// </summary>
        /// <returns>A centroid.</returns>
        public Point2 GetCentroid()
        {
            if (Count > 0)
            {
                if (Count == 1)
                {
                    return this[0].GetCentroid();
                }
                double asum = 0;
                double xsum = 0;
                double ysum = 0;
                foreach (Ring2 ring in this)
                {
                    double a = ring.GetArea();
                    Point2 p = ring.GetCentroid();
                    xsum += p.X * a;
                    ysum += p.Y * a;
                    asum += a;
                }
                if (0 != asum)
                {
                    return new Point2(xsum / asum, ysum / asum);
                }
            }
            return Point2.Invalid;
        }
        IPoint2<double> IHasPlanarCentroid<double>.GetCentroid()
        {
            return GetCentroid();
        }
        /// <summary>
        /// Calculates a minimum bounding rectangle for this polygon.
        /// </summary>
        /// <returns>A minimum bounding rectangle.</returns>
        public Mbr GetMbr()
        {
            if (Count > 0)
            {
                Mbr mbr = this[0].GetMbr();
                for (int i = 1; i < Count; i++)
                {
                    mbr = mbr.Union(this[i].GetMbr());
                }
                return mbr;
            }
            return Mbr.Invalid;
        }
        IMbr<double> IHasMbr<double>.GetMbr()
        {
            return GetMbr();
        }

        /// <summary>
        /// Determines if another point intersects this polygon.
        /// </summary>
        /// <param name="p">A point to test intersection with.</param>
        /// <returns>True when a point intersects this object.</returns>
        public bool Intersects(Point2 p)
        {
            int crossCount = 0;
            bool hasUnconstrainedHoles = false;
            List<Ring2> fillRings = new List<Ring2>(
                this.Where(r => !r.Hole.HasValue || !r.Hole.Value)
            );
            foreach (Ring2 r in this)
            {
                if (r.Count > 0)
                {
                    int isecCount = r.IntersectionPosXRayCount(p);
                    crossCount += isecCount;
                    bool isHole = r.Hole.HasValue && r.Hole.Value;
                    if (isHole && !hasUnconstrainedHoles)
                    {
                        bool contained = false;
                        Point2 hp = r.First();
                        foreach (Ring2 fill in fillRings)
                        {
                            if (fill.Intersects(hp))
                            {
                                contained = true;
                                break;
                            }
                        }
                        if (!contained)
                        {
                            hasUnconstrainedHoles = true;
                        }
                    }
                }
            }
            return (hasUnconstrainedHoles ? 0 : 1) == (crossCount % 2);
        }
        /// <summary>
        /// Determines if another point intersects this polygon.
        /// </summary>
        /// <param name="p">A point to test intersection with.</param>
        /// <returns>True when a point intersects this object.</returns>
        public bool Intersects(IPoint2<double> p)
        {
            return Intersects(new Point2(p));
        }

        /// <summary>
        /// Calculates the distance between this polygon and a point, <paramref name="p"/>. 
        /// </summary>
        /// <param name="p">The point to calculate distance to.</param>
        /// <returns>The distance between this polygon and <paramref name="p"/>.</returns>
        public double Distance(Point2 p)
        {
            return System.Math.Sqrt(DistanceSquared(p));
        }
        /// <summary>
        /// Calculates the distance between this polygon and a point, <paramref name="p"/>. 
        /// </summary>
        /// <param name="p">The point to calculate distance to.</param>
        /// <returns>The distance between this polygon and <paramref name="p"/>.</returns>
        public double Distance(IPoint2<double> p)
        {
            return Distance(new Point2(p));
        }
        /// <summary>
        /// Calculates the squared distance between this polygon and a point, <paramref name="p"/>. 
        /// </summary>
        /// <param name="p">The point to calculate squared distance to.</param>
        /// <returns>The squared distance between this polygon and <paramref name="p"/>.</returns>
        public double DistanceSquared(Point2 p)
        {
            if (Count > 0)
            {
                double d = this[0].DistanceSquared(p);
                for (int i = 1; i < Count; i++)
                {
                    d = System.Math.Min(d, this[i].DistanceSquared(p));
                }
                return d;
            }
            return Double.NaN;
        }
        /// <summary>
        /// Calculates the squared distance between this polygon and a point, <paramref name="p"/>. 
        /// </summary>
        /// <param name="p">The point to calculate squared distance to.</param>
        /// <returns>The squared distance between this polygon and <paramref name="p"/>.</returns>
        public double DistanceSquared(IPoint2<double> p)
        {
            return DistanceSquared(new Point2(p));
        }
        /// <summary>
        /// Calculates the area of this polygon.
        /// </summary>
        /// <returns>The area.</returns>
        public double GetArea()
        {
            double sum = 0;
            for (int i = 0; i < Count; i++)
            {
                Ring2 r = this[i];
                sum += r.GetArea();
            }
            return sum;
        }
        /// <summary>
        /// Determines the perimeter of this polygon.
        /// </summary>
        /// <returns>The perimeter of this polygon.</returns>
        public double GetMagnitude()
        {
            return this.Sum(r => r.GetMagnitude());
        }
        double IHasMagnitude<double>.GetMagnitudeSquared()
        {
            double m = GetMagnitude();
            return m*m;
        }
        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <returns>
        /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(Polygon2 other)
        {
            if (ReferenceEquals(this, other))
            {
                return true;
            }
            if (ReferenceEquals(null, other))
            {
                return false;
            }
            if (Count == other.Count)
            {
                for (int i = 0; i < Count; i++)
                {
                    if (!this[i].Equals(other[i]))
                    {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
        /// <summary>
        /// Creates an identical polygon.
        /// </summary>
        /// <returns>A polygon.</returns>
        public Polygon2 Clone()
        {
            Polygon2 p = new Polygon2(Count);
            foreach(Ring2 r in this)
            {
                p.Add(r.Clone());
            }
            return p;
        }
        object ICloneable.Clone()
        {
            return Clone();
        }

        public override bool Equals(object obj)
        {
            return null != obj
                && (
                    (obj is Polygon2 && Equals(obj as Polygon2))
                )
            ;
        }

        public override int GetHashCode()
        {
            return GetMbr().GetHashCode() ^ -1111034994;
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return (
                1 == Count
                ? "Polygon, 1 Ring"
                : String.Concat("Polygon, ", Count, " Ring")
            );
        }

        /// <summary>
        /// Determines if the given MBR contains this polygon.
        /// </summary>
        /// <param name="mbr">The MBR to test.</param>
        /// <returns>True if this polygon is within the given MBR.</returns>
        public bool Within(Mbr mbr)
        {
            return GetMbr().Within(mbr);
        }
        /// <summary>
        /// Determines if the given MBR contains this polygon.
        /// </summary>
        /// <param name="mbr">The MBR to test.</param>
        /// <returns>True if this polygon is within the given MBR.</returns>
        public bool Within(IMbr<double> mbr)
        {
            return GetMbr().Within(mbr);
        }

        /// <summary>
        /// Determines if this polygon is self-intersecting.
        /// </summary>
        /// <returns>True if self-intersecting.</returns>
        public bool IsSelfIntersecting()
        {
            throw new NotImplementedException();
        }
    }
}
